<?php

namespace app\api\controller;

use app\api\service\ProductService;
use app\common\controller\ApiBase;
use app\common\model\user\Artwork as UserArtworkModel;
use app\common\model\user\ArtworkAttribute as UserArtworkAttributeModel;
use app\common\validate\user\ArtworkAttribute as ArtworkAttributeValidate;
use think\Db;
use think\Exception;

class ArtworkAttribute extends ApiBase
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    //添加
    public function add()
    {
        $this->checkRequestParam(ArtworkAttributeValidate::class);

        if ($this->request->param('pmat_key')) {
            $userArtworkAttribute = UserArtworkAttributeModel::where([
                'mat_key'    => $this->request->param('pmat_key'),
                'artwork_id' => $this->request->param('artwork_id'),
            ])->find();
            if (!$userArtworkAttribute) {
                $this->error('pmat_key错误');
            }
        }

        $artwork = UserArtworkModel::where([
            'id'      => $this->request->param('artwork_id'),
            'user_id' => $this->auth->id,
        ])->find();
        if (!$artwork) {
            $this->error('作品不存在');
        }

        $service = new ProductService;
        $product = $service->getProductById($this->request->param('product_id'));
        if (!$product) {
            $this->error($service->getMsg());
        }
        $userArtwork = UserArtworkAttributeModel::create([
            'artwork_id' => $artwork->id,
            'mat_key'    => $this->request->param('mat_key/d',0),
            'pmat_key'   => $this->request->param('pmat_key/d',0),
            'product_id' => $product->id,
            'fbx_id'     => $product->fbx_id,
            'position'   => $this->request->param('position/a'),
            'rotation'   => $this->request->param('rotation/a'),
            'proportion' => $this->request->param('proportion'),
        ]);

        if ($userArtwork) {
            $this->success('success', ['user_artwork' => $userArtwork]);
        } else {
            $this->error('保存失败');
        }
    }

    public function edit()
    {
        $this->checkRequestParam(ArtworkAttributeValidate::class);

        if ($this->request->param('pmat_key') ) {
            $userArtworkAttribute = UserArtworkAttributeModel::where([
                'mat_key'    => $this->request->param('pmat_key'),
                'artwork_id' => $this->request->param('artwork_id'),
            ])->find();
            if (!$userArtworkAttribute) {
                $this->error('pmat_key错误');
            }
        }

        $artwork = UserArtworkModel::where([
            'id'      => $this->request->param('artwork_id'),
            'user_id' => $this->auth->id,
        ])->find();
        if (!$artwork) {
            $this->error('作品不存在');
        }

        $alias = 'artwork_attribute';
        $userArtworkAttribute = UserArtworkAttributeModel
            ::alias($alias)->where([$alias . '.id' => $this->request->param('id')])
            ->with([
                'artwork' => function ($query) {
                    $query->where([
                        'artwork.id'      => $this->request->param('artwork_id'),
                        'artwork.user_id' => $this->auth->id,
                    ]);
                }
            ])
            ->find();

        if (!$userArtworkAttribute) {
            $this->error('数据不存在');
        }

        $userArtworkAttribute->mat_key = $this->request->param('mat_key/d',0);
        $userArtworkAttribute->pmat_key = $this->request->param('pmat_key/d',0);
        $userArtworkAttribute->position = $this->request->param('position/a');
        $userArtworkAttribute->rotation = $this->request->param('rotation/a');
        $userArtworkAttribute->proportion = $this->request->param('proportion');
        if ($userArtworkAttribute->save()) {
            UserArtworkModel::updateVersion($artwork['id']);  //artwork版本+1
            $this->success('success', ['user_artwork' => $userArtworkAttribute]);
        } else {
            $this->error('保存失败');
        }
    }

    // 删除
    public function del()
    {
        $this->checkRequestParam(ArtworkAttributeValidate::class);
        $alias = 'artwork_attribute';
        $list = UserArtworkAttributeModel
            ::alias($alias)->where([$alias . '.id' => ['in', explode(',', $this->request->param('ids'))]])
            ->with([
                'artwork' => function ($query) {
                    $query->where([
                        'artwork.id'      => $this->request->param('artwork_id'),
                        'artwork.user_id' => $this->auth->id,
                    ]);
                }
            ])
            ->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            UserArtworkModel::updateVersion($this->request->param('artwork_id'));  //artwork版本+1
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success('删除成功', ['count' => $count]);
        } else {
            $this->error('删除失败');
        }
    }

    //批量操作
    public function batch()
    {
        $artwork = UserArtworkModel::where([
            'id'      => $this->request->param('artwork_id/d'),
            'user_id' => $this->auth->id,
        ])->find();
        if (!$artwork) {
            $this->error('作品不存在');
        }

        $data = $this->request->param('data/a', []);
        if (!$data) {
            $this->error('缺少参数');
        }

        // 检查 product_id
        $product_ids = array_unique(array_column($data, 'product_id'));
        $service = new ProductService;
        $products = $service->getProductsByIds($product_ids);
        if (!$products) {
            $this->error($service->getMsg());
        }


        $batchDatas = [];
        foreach ($data as &$item) {
            $item['artwork_id'] = $artwork['id'];
            $this->checkRequestParam(ArtworkAttributeValidate::class, $item);
            $batchDatas[] = [
                'artwork_id' => $artwork['id'],
                'mat_key'    => $item['mat_key'],
                'pmat_key'   => $item['pmat_key'],
                'product_id' => $products[$item['product_id']]['id'],
                'fbx_id'     => $products[$item['product_id']]['fbx_id'],
                'position'   => $item['position'],
                'rotation'   => $item['rotation'],
                'proportion' => $item['proportion'],
            ];
        }

        $userArtworkAttribute = new UserArtworkAttributeModel;
        Db::startTrans();
        try {
            UserArtworkAttributeModel::where(['artwork_id' => $artwork['id']])->delete();
            $flag = $userArtworkAttribute->saveAll($batchDatas);
            if ($flag) {
                UserArtworkModel::updateVersion($artwork['id']);  //artwork版本+1
                Db::commit();
                $this->success('批量修改成功', $flag);
            } else {
                Db::rollback();
                $this->error('批量修改失败', $batchDatas);
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->errorTrace('批量修改失败', $e);
        }

    }
}
